package com.ai.ubssapp.util;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

/**
 * 增加可以指定字符集的响应处理器
 * 
 * @author MQK
 */
public class CharsetResponseHandler implements ResponseHandler<String> {
	
	private String charset;
	
	public CharsetResponseHandler(String charset) {
		this.charset = charset;
	}

	@Override
	public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {

		HttpEntity entity = response.getEntity();
		String responseBody = entity != null ? EntityUtils.toString(entity, this.charset) : null;
		int status = response.getStatusLine().getStatusCode();
		if (status >= 200 && status <= 300) {
			return responseBody;
		} else if(status == 301 || status == 302){
			return "错误：发生了重定向，登录状态失效！";
		} else {
			throw new ClientProtocolException("Unexpected response status: " + status + "\nresponseBody:" + responseBody);
		}
	}

}
